/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.tracer.core.internals;

import com.lvyh.lightframe.tracer.core.exception.TraceRuntimeException;
import com.lvyh.lightframe.tracer.core.spi.ServiceBootstrap;

/**
 * Configinjector injector to implement dependency injection
 * In META-INF/services/com.lvyh.lightframe.client.internals.Injector, the implementation class of the configuration injector is DefaultConfigInjector.
 */
public class ConfigInjector {

    /**
     * injector
     */
    private static volatile BaseInjector injector;

    private static final Object lock = new Object();

    private static BaseInjector getInjector() {
        if (injector == null) {
            synchronized (lock) {
                if (injector == null) {
                    try {
                        //Loading the corresponding injector implementation object based on JDK SPI
                        injector = ServiceBootstrap.loadFirst(BaseInjector.class);
                    } catch (Throwable ex) {
                        throw new TraceRuntimeException("Unable to initialize config injector!", ex);
                    }
                }
            }
        }

        return injector;
    }

    public static <T> T getInstance(Class<T> clazz) {
        try {
            return getInjector().getInstance(clazz);
        } catch (Throwable ex) {
            throw new TraceRuntimeException(String.format("Unable to load instance for type %s!", clazz.getName()), ex);
        }
    }

}
